package com.bonait.hotapp.utils;

import android.annotation.SuppressLint;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PathUtils;
import com.bonait.hotapp.entity.vo.UpdateVO;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.download.Callback;

import java.io.File;

public class UpdateUtil {

    private UpdateListener updateListener;

    //private final String SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "patch"; // 储存下载文件的路径
    private final String SAVE_PATH = PathUtils.getExternalAppFilesPath() + "/" + "patch"; // 储存下载文件的路径

    private String appUrl = "http://222.222.17.184:8881/resource/app/apk/20220514134520669/社区管家20.apk";

//    private String appUrl = "https://gwdl.coral3.com/patch/patch_signed_7zip.apk";
    //private String resUrl = "https://gwdl.coral3.com/patch/patch_signed_7zip.apk";

//    private String appUrl = "https://gitee.com/itchenqi188/my1-application/raw/master/patch_signed_7zip.apk";
//    private String resUrl = "https://gitee.com/itchenqi188/my1-application/raw/master/patch_signed_7zip.apk";

    //http://192.168.100.243:8080/day08/patch_signed_7zip.apk
    //private String appUrl = "http://192.168.100.243:8080" + File.separator + "day08" + File.separator + "patch_signed_7zip.apk";
    private String resUrl = "patch_signed_7zip.apk";


    private File file;
    private static UpdateUtil updateUtil;

    public UpdateUtil(UpdateListener updateListener) {
        this.updateListener = updateListener;
    }

    public static UpdateUtil newInstance(UpdateListener updateListener) {
        if (updateUtil == null) updateUtil = new UpdateUtil(updateListener);
        return updateUtil;
    }

    public interface UpdateListener {
        void DownloadSuccess(String resUrl);//成功返回

        void DownloadFailure(String err);//失败返回
    }

    private void update() {
        startDownload();
    }

    public void startDownload() {
        OkHttpDownload(getUpdateModel());
    }

    private UpdateVO getUpdateModel() {
        UpdateVO updateModel = new UpdateVO();
        updateModel.setAppUrl(appUrl);
        updateModel.setResUrl(resUrl);
        return updateModel;
    }

    /**
     * @author : wty
     * @time : 2020/11/5
     * @name : downloadFile
     * @Parameters : [url]
     * @describe :下载文件
     */
    @SuppressLint("NewApi")
    public void OkHttpDownload(UpdateVO updateModel) {

        Kalle.Download.get(appUrl)//
                .directory(PathUtils.getExternalAppFilesPath() + "/" + "patch")
                .fileName(resUrl)//
                .perform(new Callback() {//

                    @Override
                    public void onStart() {//
                        //下载之前的其他操作内容
                    }

                    @Override
                    public void onFinish(String filePath) {

                        // 请求完成，文件路径：path。
                        LogUtils.d("itchen--->下载 成功了=>" + filePath);
                        //    │ itchen--->下载 成功了=>/storage/emulated/0/Android/data/com.bonait.hotapp/files/patch/patch_signed_7zip.apk

                        Delivery.getInstance().post(new Runnable() {

                            @Override
                            public void run() {

                                //下载成功
                                updateListener.DownloadSuccess(filePath.toString());

                            }
                        });


                    }

                    @Override
                    public void onException(Exception e) {

                        if (!ObjectUtils.isEmpty(e)) {
                            //LogUtils.d("itchen---->下载出错==>" + e.getLocalizedMessage());
                            LogUtils.d("itchen---->下载出错==>" + e.getMessage().toString());
                        }

                    }

                    @Override
                    public void onCancel() {
                        LogUtils.d("itchen---->下载onCancel--取消了-->");
                    }

                    @Override
                    public void onEnd() {
                        LogUtils.d("itchen---->下载 onEnd-完毕了--->");


                    }
                });


//        OkHttpClient okHttpClient = new OkHttpClient();
//
//        LogUtils.d("itchen--->yue-tag", "开始下载:" + updateModel.getAppUrl());
//        //Request request = new Request.Builder().url(updateModel.getResUrl()).build();
//        //Request request = new Request.Builder().url("http://192.168.100.243:8080/day08/patch_signed_7zip.apk").build();
//        Request request = new Request.Builder().url(appUrl).build();
//        LogUtils.d("itchen---request.url().toString()==>" + request.url().toString());
//
//
//        okHttpClient.newCall(request).enqueue(new Callback() {
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                //请求失败
//                updateListener.DownloadFailure("failure");
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                //请求成功
//                InputStream inputStream = null;
//                FileOutputStream fileOutputStream = null;
//
//                LogUtils.d("itchen----yue-tag", "请求成功");
//
//                byte[] bytes = new byte[1024 * 10];
//                int length = 0;
//                file = new File(SAVE_PATH);
//                if (!file.exists()) { //文件夹不存在
//                    // 创建文件夹
//                    file.mkdirs();
//                }
//                try {
//                    inputStream = response.body().byteStream();
//                    file = new File(SAVE_PATH, updateModel.getResName());
//                    fileOutputStream = new FileOutputStream(file);
//                    while ((length = inputStream.read(bytes)) != -1) {
//                        fileOutputStream.write(bytes, 0, length);
//                    }
//                    fileOutputStream.flush();
//                    //下载成功
//                    updateListener.DownloadSuccess(file.getPath());
//
//                } catch (Exception e) {
//
//                    LogUtils.d("itchen----yue-tag", "下载失败--->" + e.getLocalizedMessage());
//
//                    e.printStackTrace();
//                    // 下载失败
//                    updateListener.DownloadFailure("failure");
//
//                } finally {
//                    if (inputStream != null) {
//                        inputStream.close();
//                    }
//
//                    if (fileOutputStream != null) {
//                        fileOutputStream.close();
//                    }
//                }
//            }
//        });
    }
}
